package com.yvan.http;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yvan.platform.JsonWapper;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

public class YvanCookieJar implements CookieJar {

    private final ConcurrentMap<String, List<Cookie>> cookiesMap = Maps.newConcurrentMap();

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        final String host = url.host();
        cookiesMap.computeIfAbsent(host, key -> Lists.newCopyOnWriteArrayList()).addAll(cookies);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        return cookiesMap.computeIfAbsent(url.host(), k -> Lists.newCopyOnWriteArrayList());
    }

    @Override
    public String toString() {
        JsonWapper jw = new JsonWapper();
        for (Map.Entry<String, List<Cookie>> entry : cookiesMap.entrySet()) {
            jw.set(entry.getKey(), entry.getValue().stream().map(Cookie::toString).toArray());
        }
        return jw.toString(true);
    }
}
